package main

import (
"fmt"
"io"
"os"
"strings"
"log"
"net/url"
"net/http"
"net/http/httputil"
)

const port = 9998
func handler(proxy *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
    return func(w http.ResponseWriter, r *http.Request) {
        log.Println(r.URL)
        reqDump, err := httputil.DumpRequest(r, true)
        if err != nil {
            log.Fatal(err)
        }

        log.Printf("request uri:%s,proto:%s,host:%s,user agent:%s, remote addr:%s, x-forwarded-for:%s", r.URL.RequestURI(), r.Proto, r.Host, r.UserAgent(), r.RemoteAddr, r.Header.Get("X-Forwarded-For"))
        
        var reqDumpStr string =  string(reqDump)
        fmt.Println("REQUST:[%s]", reqDumpStr)
        fmt.Println("\n")

        var fileContent string
        if strings.Contains(reqDumpStr, "...") {
            fileContent = readfile("...")
        }

        if fileContent != "" {
            fmt.Println(fileContent)
            w.Write([]byte(fileContent))
        } else {
            proxy.ServeHTTP(w, r)
        }
    }
}

func readfile(fileName string) string {
    file, err := os.Open(fileName)
    if err != nil {
        fmt.Println(err)
        return ""
    }

    defer file.Close()

    buf := make([]byte, 1024)
    var bytes []byte

    for {
        count, err := file.Read(buf) 
        if err == io.EOF {
            break;
        }

        fmt.Println("bytedata:", buf)
        fmt.Println("stringdat:", string(buf))
        fmt.Println("stringcnt:", count)

        currBytes := buf[:count] 
        bytes = append(bytes, currBytes...)
    }

    fmt.Println(string(bytes))
    return string(bytes);
}

 
func main() {
    remote, err1 := url.Parse("http://localhost:9999/")
    if err1 != nil {
        log.Fatalln(err1.Error())
    }

    proxy := httputil.NewSingleHostReverseProxy(remote)

    http.HandleFunc("/", handler(proxy))
    err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
    if err != nil {
        log.Fatalln(err.Error())
    } else {
        log.Printf("Starting http server at port:%d\n", port)
    }
}

